<template>
  <div :key="key">
    <el-tabs type="border-card">
      <div
        style="width: auto;height: 190px;background-color:#f2dede;border-radius: 3px;color: #b94a48;padding: 15px; margin-bottom: 20px;border:#ebcdcd">

        <p><b>温馨提示</b></p>
        <p><b>模板信息可以让老师或学生家长收到相关的提醒，如通知提醒、作业提醒等</b></p>
        <p><b>1、申请微信公众号（服务号）并认证，如果已有可不用申请</b></p>
        <p><b>模板信息为微信公众号（服务号）的功能，因此您的小程序需要关联服务号</b></p>
        <p><b>您的微信公众号（服务号）认证通过后，设置行业“IT科技/IT软件与服务”及“教育/培训”</b></p>
        <p><b>在左侧菜单“广告与服务-模板信息中”中，添加以下模板信息（添加时注意与示例图中的格式一致），将模板信息ID修改为您相应的模板信息ID</b></p>

      </div>
      <!-- <el-tab-pane label="全部"> -->
      <div v-if="seek" style="margin: 20px 0px;">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" size="medium">


          <el-form-item label="ID">
            <el-input v-model="formInline.id" placeholder="ID"></el-input>
          </el-form-item>
          <el-form-item label="标题">
            <el-input v-model="formInline.title" placeholder="标题"></el-input>
          </el-form-item>

          <el-form-item label="用处">
            <el-input v-model="formInline.use" placeholder="用处"></el-input>
          </el-form-item>

          <el-form-item label="模板ID">
            <el-input v-model="formInline.templateid" placeholder="模板ID"></el-input>
          </el-form-item>
          <el-form-item label="模板示意图">
            <el-input v-model="formInline.templateimg" placeholder="模板示意图"></el-input>
          </el-form-item>
          <el-form-item label="启用">
            <el-select v-model="formInline.region" placeholder="选择">
              <el-option label="是" value="shanghai"></el-option>
              <el-option label="否" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="更新时间">
            <el-input v-model="formInline.turnover_time" placeholder="更新时间"></el-input>
          </el-form-item>

          <br />

          <el-form-item>
            <el-button type="success" @click="inquire" style="background-color: #18bc9c;">提交</el-button>
            <el-button type="info" @click="reset" style="background-color: #f4f4f4;color: black;">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- <el-button type="info" :loading="true" size="small"></el-button> -->
      <ModalBox>
        <!--  <template v-slot:s1 >
                <el-button type="success" icon="el-icon-edit" size="small" style="background-color: #18bc9c;" @click="dialogVisible = true">编辑</el-button>
                </template>  -->
      </ModalBox>




      <el-button type="info" icon="el-icon-search" plain style="float: right" @click="seek = !seek"
        size="small"></el-button>
      <el-button-group style="float: right">
        <el-button type="info" icon="el-icon-s-order" plain size="small"></el-button>

        <el-button type="info" plain size="small"><el-popover placement="bottom" title="筛选列" trigger="click" width="40">
            <el-checkbox-group v-model="checkedColumns" size="small">
              <el-checkbox v-for="item in checkBoxGroup" :key="item" :label="item" :value="item"></el-checkbox>
            </el-checkbox-group>
            <div title="筛选列" class="filter-table-col" slot="reference">
              <i class="el-icon-s-grid"> </i>
            </div>
          </el-popover></el-button>
        <el-button type="info" icon="el-icon-upload2" plain size="small">
        </el-button>
      </el-button-group>
      <el-input placeholder="搜索" v-model="input" clearable style="width: 195px; float: right" size="small">
      </el-input>
      <!-- 表格 -->
      <div class="tableDemo">
        <el-table :data="tableData.slice(
          (currentPage - 1) * pagesize,
          currentPage * pagesize
        )
          " style="width: 100%">
          <el-table-column type="selection" align="center"> </el-table-column>
          <!-- 对数据的处理，最最最重要的一句话 -->
          <el-table-column v-if="colData[0].istrue" prop="id" label="ID" sortable align="center">
          </el-table-column>
          <el-table-column v-if="colData[1].istrue" prop="title" label="标题" sortable align="center">
          </el-table-column>
          <el-table-column v-if="colData[2].istrue" prop="use" label="用处" sortable align="center">
          </el-table-column>
          <el-table-column v-if="colData[3].istrue" prop="templateid" label="模板ID" sortable align="center">
          </el-table-column>

          <el-table-column v-if="colData[4].istrue" prop="templateimg" label="模板示意图" align="center">
            <template slot-scope="scope">
              <el-image style="width: 50px; height: 50px" :src="scope.row.templateimg"
                :preview-src-list="[scope.row.templateimg]"></el-image>
            </template>
          </el-table-column>
          <el-table-column v-if="colData[5].istrue" prop="enable" label="启用" sortable align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.enable" active-color="#13ce66" inactive-color="#ff4949" active-value="100"
                inactive-value="0">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column v-if="colData[6].istrue" prop="turnover_time" label="更新时间" sortable width="180" align="center">
          </el-table-column>

          <el-table-column v-if="colData[7].istrue" label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row.id)" class="el-icon-edit"
                style="background-color: #18bc9c;color: #fff;"></el-button>

            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" align="right"
          :current-page="currentPage" :page-sizes="[5, 10, 20, 40]" :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
        </el-pagination>
      </div>


    </el-tabs>

    <!-- 编辑 -->
    <el-dialog v-dialogDrag ref="xhzqDialog" class="xhzqDialog" :title="title" :fullscreen="isfullscreen"
      :visible.sync="dialogVisible" :append-to-body="true" :close-on-click-modal="false" :show-close="false"
      :width="width" :class="isminimize ? 'isminimize' : ''" center>
      <div v-show="!isminimize" slot="title" class="medium">
        <span style="color: #fff;float: left;margin-left: 20px;">编辑</span>
        <div class="centers"><span>{{ title }}</span></div>
        <div class="icons">
          <!-- <span style="color: #fff;float: left;">编辑</span> -->
          <i class="el-icon-minus" style="font-size: 24px" @click="minimize"></i>
          <i :class="isfullscreen ? 'el-icon-crop' : 'el-icon-full-screen'" style="font-size: 24px"
            @click="IsFullscreen"></i>
          <i class="el-icon-close" style="font-size: 24px" @click="closeDialog"></i>
        </div>
      </div>
      <div v-show="isminimize" slot="title" class="horn">
        <div class="lefts"><span>{{ title }}</span></div>
        <div class="centers"><i class="el-icon-full-screen" style="font-size: 24px" @click="minimize"></i></div>
        <div class="rights"><i class="el-icon-close" style="font-size: 24px" @click="closeDialog"></i></div>
      </div>
      <div v-show="!isminimize" class="dialogBody">
        <slot>
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="标题:">
              <el-input v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item label="用处:">
              <el-input v-model="form.use"></el-input>
            </el-form-item>
            <el-form-item label="模板ID:">
              <el-input v-model="form.templateid"></el-input>
            </el-form-item>
            <el-form-item label="启用:">
              <el-radio-group :v-model="form.enable == '100' ? label1 = '0' : label2 = '100'">
                <el-radio v-model="radio" label="1">禁用</el-radio>
                <el-radio v-model="radio" label="2">启用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="示意图：">
              <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisibles">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>



          </el-form>
        </slot>
      </div>
      <div v-show="!isminimize" v-if="isFooter" class="dialogFooter" style=" background-color: #ecf0f1;">
        <slot name="footer" solt="footer">

          <div style="margin-right: 70%;">
            <el-button type="success" style="background-color: #18bc9c;" @click="ok">确定</el-button>
            <el-button type="success" style="background-color: #18bc9c;" @click="resets">重置</el-button>
          </div>

        </slot>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { Template } from "../../request/api.js";
import ModalBox from "@/components/ModalBox";
// Vue.forceUpdate()

export default {
  name: "ClassPROJECTIndex",

  data() {
    return {
      imageUrl: '',
      radio: '1',
      key: 0,
      dialogVisible: false,
      currentPage: 1, //初始页
      pagesize: 5, //    每页的数据
      input: "",
      seek: false,
      tableData: [],
      formInline: {
        id: '',
        title: '',
        use: "",
        templateid: '',
        templateimg: '',
        enable: '',
        turnover_time: ''
      },
      colData: [
        { title: "ID", istrue: true },
        { title: "标题", istrue: true },
        { title: "用处", istrue: true },
        { title: "模板ID", istrue: true },
        { title: "模板示意图", istrue: true },
        { title: "启用", istrue: true },
        { title: "更新时间", istrue: true },
        { title: "操作", istrue: true },

        // { title: "服务器类型", istrue: true },
      ],

      // 多选框的列表，列出表格的每一列
      checkBoxGroup: [
        "ID",
        "标题",
        "用处",
        "模板ID",
        "模板示意图",
        "启用",
        "更新时间",
        "操作",
      ],
      // 当前选中的多选框，代表当前展示的列
      checkedColumns: [
        "ID",
        "标题",
        "用处",
        "模板ID",
        "模板示意图",
        "启用",
        "更新时间",
        "操作",
      ],
      isfullscreen: false, // 全屏
      isminimize: false, // 最小化
      dialogVisible: false, // 隐藏弹窗
      dialogImageUrl: '',
      dialogVisibles: false,
      disabled: false,
      form: {
        id: '',
        name: '',
        title: '',
        use: '',
        templateid: '',
        templateimg: '',
        enable: '',
        turnover_time: '',



      }
    };
  },
  created() {
    Template().then((res) => {
      this.tableData = res.data;
    });
  },

  props: {
    width: {
      type: String,
      default: '50%'
    },
    title: {
      type: String,
      default: ''
    },
    isFooter: { // 是否显示脚部
      type: Boolean,
      default: true
    }
  },
  watch: {
    checkedColumns(val) {
      let arr = this.checkBoxGroup.filter((i) => !val.includes(i));
      this.colData.filter((i) => {
        if (arr.indexOf(i.title) != -1) {
          i.istrue = false;
        } else {
          i.istrue = true;
        }
      });
      this.reload = Math.random();
    },
    dialogVisible(val) {
      if (val) {
        const el = this.$refs.xhzqDialog.$el.querySelector('.el-dialog')
        el.style.left = 0
        el.style.top = 0
      }
    }
  },

  mounted() { },

  methods: {
    onSubmit() {
      console.log("submit!");
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange(size) {
      this.pagesize = size; //将每页显示的条数 = 改变的值
      console.log(this.pagesize); //每页下拉显示数据
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage; //然后将当前页 = 改变的值
      console.log(this.currentPage); //点击第几页
    },
    formatter(row, column) {
      return row.address;
    },
    inquire() {
      Template().then((res) => {
        let data = res.data;
        let array = []
        for (let i = 0; i < data.length; i++) {
          if (this.formInline.id == data[i].id || data[i].title.indexOf(this.formInline.title) != -1 || this.formInline.use == data[i].use || this.formInline.templateid == data[i].templateid || this.formInline.templateimg == data[i].templateimg || this.formInline.enable == data[i].enable || this.formInline.turnover_time == data[i].turnover_time) {
            array.push(data[i])

          }

        }
        this.tableData = array

      });
    },
    reset() {
      this.formInline.id = '',
        this.formInline.title = '',
        this.formInline.use = '',
        this.formInline.templateid = '',
        this.formInline.templateimg = '',
        this.formInline.enable = '',
        this.formInline.turnover_time = '',
        this.$forceUpdate()
      // this.key += 1 
      // this.$router.go(0)
    },
    handleEdit(a, b) {
      alert(a, b)
      let id = a + 1
      this.dialogVisible = true
      Template().then((res) => {
        let data = res.data;
        let array = {}
        for (let i = 0; i < data.length; i++) {
          if (id == data[i].id) {
            array = data[i]
          }
        }
        this.form.title = array.title,
          this.form.use = array.use,
          this.form.templateid = array.templateid,
          this.form.enable = array.enable,
          this.imageUrl = array.templateimg
      });

    },

    // 最小化
    minimize() {
      this.isminimize = !this.isminimize
      if (this.isfullscreen) this.isfullscreen = !this.isfullscreen
    },
    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false
    },
    // 打开弹窗
    openDialog() {
      this.dialogVisible = true
    },
    // 全屏
    IsFullscreen() {
      this.isfullscreen = !this.isfullscreen
      if (this.isfullscreen) this.$emit('isfullscreen')
    },
    onSubmit() {
      console.log('submit!');
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibles = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    ok() {
      this.dialogVisible = false;
      this.$message.success('操作成功');
    },
    resets() {
      this.dialogVisible = false;
      this.$message.success('操作成功');
    },

    handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    
  },
  // 编辑模态框
  directives: {
    dialogDrag: {
      bind(el, binding, vnode, oldVnode) {
        const dialogHeaderEl = el.querySelector('.el-dialog__header')
        const dragDom = el.querySelector('.el-dialog')
        dialogHeaderEl.style.cursor = 'move'
        // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
        const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null)
        // const fixedX =
        // const fixedY =
        dialogHeaderEl.onmousedown = (e) => {
          // 判断当前是否为全屏状态
          const path = event.path || (event.composedPath && event.composedPath())
          const isFull = path.find(s => {
            if (s.className === undefined) {
              return false
            } else {
              return s.className.indexOf('is-fullscreen') > -1
            }
          })
          if (isFull !== undefined) {
            return
          }
          const isMinix = path.find(s => {
            if (s.className === undefined) {
              return false
            } else {
              return s.className.indexOf('isminimize') > -1
            }
          })
          if (isMinix !== undefined) {
            return
          }
          // 鼠标按下，计算当前元素距离可视区的距离
          const disX = e.clientX - dialogHeaderEl.offsetLeft
          const disY = e.clientY - dialogHeaderEl.offsetTop

          // 获取到的值带px 正则匹配替换
          let styL, styT

          // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
          if (sty.left.includes('%')) {
            styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100)
            styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
          } else {
            styL = +sty.left.replace('px', '')
            styT = +sty.top.replace('px', '')
          }

          document.onmousemove = function (e) {
            // 通过事件委托，计算移动的距离
            const l = e.clientX - disX
            const t = e.clientY - disY
            // 移动当前元素
            dragDom.style.left = `${l + styL}px`
            dragDom.style.top = `${t + styT}px`
            // const dom = e.path.find(s => s.querySelector('.el-dialog')).children[0]
            //
            // if (dom.offsetTop < 0) {
            //   dragDom.style.top = `0px`
            // }
            // if (dom.offsetLeft < 0) {
            //   dragDom.style.left = `0px`
            // }

            // 将此时的位置传出去
            // binding.value({x:e.pageX,y:e.pageY})
          }

          document.onmouseup = function (e) {
            const dragDom = el.querySelector('.el-dialog')
            const offsetLeft = dragDom.offsetLeft
            const offsetTop = dragDom.offsetTop
            const left = Number(dragDom.style.left.replace('px', ''))
            const top = Number(dragDom.style.top.replace('px', ''))
            const windowWidth = window.innerWidth
            const windowHeight = window.innerHeight - 50
            const offsetRight = offsetLeft + dragDom.offsetWidth - windowWidth
            const offsetBottom = offsetTop + dragDom.offsetHeight - windowHeight
            if (offsetLeft < 0) {
              dragDom.style.left = (left - offsetLeft) + 'px'
            }
            if (offsetTop < 0) {
              dragDom.style.top = (top - offsetTop) + 'px'
            }
            if (offsetRight > 0) {
              dragDom.style.left = (left - offsetRight) + 'px'
            }
            if (offsetBottom > 0) {
              dragDom.style.top = (top - offsetBottom) + 'px'
            }
            document.onmousemove = null
            document.onmouseup = null
          }
        }
      }
    }
  },
  //   挂载
  components: {
    ModalBox
  }
};
</script>

<style>
p {
  margin-bottom: 10px;
}
</style>